/**
 * 实现语音识别子服务
 */

#ifndef ASR_SERVER_ASR_SERVER_H
#define ASR_SERVER_ASR_SERVER_H

#include <brpc/server.h>
#include <butil/logging.h>

#include <memory>

#include "asr.h"
#include "etcd.h"
#include "speech.pb.h"

namespace chat {
class ASRServerImpl : public SpeechService {
   public:
    ASRServerImpl(BaiDuYunASRClientPtr client);

    void SpeechRecognition(::google::protobuf::RpcController* controller,
                           const ::chat::SpeechRecognitionReq* request,
                           ::chat::SpeechRecognitionRsp* response,
                           ::google::protobuf::Closure* done);

   private:
    BaiDuYunASRClientPtr client_ = nullptr;
};

class ASRServer {
   public:
    ASRServer(const BaiDuYunASRClientPtr& asr_client,
              const RegistryPtr& register_client,
              const std::shared_ptr<brpc::Server> brpc_server)
        : asr_client_(asr_client),
          register_client_(register_client),
          brpc_server_(brpc_server) {}

    /**
     * @brief 启动rpc服务
     */
    void start();

   private:
    BaiDuYunASRClientPtr asr_client_ = nullptr;
    RegistryPtr register_client_ = nullptr;
    std::shared_ptr<brpc::Server> brpc_server_ = nullptr;
};

using ASRServerPtr = std::shared_ptr<ASRServer>;

class ASRServerBuilder {
   public:
    /**
     * @brief 创建asr语音识别客户端
     */
    void makeAsrClient(const std::string& app_id, const std::string& app_key,
                       const std::string& secret_key);

    /**
     * @brief 创建服务注册客户端
     * @param register_name[in]: 服务名称
     * @param etcd_host[in]: etcd服务器 ip:port
     * @param access_host[in]: 外部访问 ip:port
     */
    void makeRegisterClient(const std::string& register_name,
                            const std::string& etcd_host,
                            const std::string& access_host);

    /**
     * @brief 创建 brpc 服务
     * @param port[in]: brpc 服务器端口
     * @param idle_timeout_sec[in]: 连接空闲超时时间，超时后连接关闭
     * @param num_threads[in]: 线程数量
     */
    void makeBrpcServer(const uint16_t port, const int idle_timeout_sec,
                        const int num_threads);

    /**
     * @brief 构造一个 ASRServer对象 并返回
     */
    ASRServerPtr build();

   private:
    BaiDuYunASRClientPtr asr_client_ = nullptr;
    RegistryPtr register_client_ = nullptr;
    std::shared_ptr<brpc::Server> brpc_server_ = nullptr;
};
}  // namespace chat

#endif  // ASR_SERVER_ASR_SERVER_H